package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Motive;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("MotiveService")
@Transactional

public class MotiveServiceImpl extends CmiEmaService implements MotiveService {
	public MotiveServiceImpl() {
	}

	@Transactional
	public Motive saveMotive(Motive motive) {
		Set<Event> existingEventsForEvent = new HashSet<Event>();

		Set<Event> selectedEventsForEvent = motive.getEventsForMotive();

		if (motive.getId() == null) {

			Motive existingMotive = motiveDAO.findMotiveByPhysicalPrimaryKey(motive.getName());

			if (isEquals(motive, existingMotive)) {
				return existingMotive;
			}

			motive = motiveDAO.store(motive);
			motiveDAO.flush();

			for (Event relatedEvent : selectedEventsForEvent) {
				relatedEvent.getMotivesForEvent().add(motive);
				eventDAO.store(relatedEvent);
			}
		} else {
			Motive existingMotive = motiveDAO.findMotiveByPrimaryKey(motive.getId());

			existingEventsForEvent = existingMotive.getEventsForMotive();

			Set<Event> prepareDeleteEventsForEvent = new HashSet<Event>();
			Set<Event> prepareAddEventsForEvent = new HashSet<Event>();

			prepareDeleteEventsForEvent.addAll(selectedEventsForEvent);
			prepareDeleteEventsForEvent.addAll(existingEventsForEvent);

			prepareAddEventsForEvent.addAll(selectedEventsForEvent);
			prepareAddEventsForEvent.addAll(existingEventsForEvent);

			prepareDeleteEventsForEvent.removeAll(selectedEventsForEvent);
			prepareAddEventsForEvent.removeAll(existingEventsForEvent);

			for (Event relatedEvent : prepareAddEventsForEvent) {

				relatedEvent.getMotivesForEvent().add(existingMotive);
				eventDAO.store(relatedEvent);
			}

			for (Event relatedEvent : prepareDeleteEventsForEvent) {

				relatedEvent.getMotivesForEvent().remove(existingMotive);
				eventDAO.store(relatedEvent);
			}
			motive = motiveDAO.store(motive);
			motiveDAO.flush();
		}

		eventDAO.flush();
		return motive;
	}

	public void deleteMotive(Motive motive) {
		motiveDAO.remove(motive);
		motiveDAO.flush();
	}

	@Transactional
	public void deleteMotives(Set<Integer> deleteMotivesId) {
		Query query = motiveDAO.createNamedQuery("deleteMotivesById", -1, -1);
		query.setParameter(1, deleteMotivesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Motive> loadMotives() {
		return motiveDAO.findAllMotives();

	}

	@Transactional
	public Set<Motive> loadReferenceMotives(Set<Motive> motives) {
		Iterator<Motive> motivesIterator = motives.iterator();
		Set<Motive> referencedMotives = new HashSet<>();
		while (motivesIterator.hasNext()) {
			Motive currentMotive = motivesIterator.next();

			if (!currentMotive.getEventsForMotive().isEmpty()) {
				referencedMotives.add(currentMotive);
				continue;
			}
		}
		return referencedMotives;
	}

	public Set<Motive> loadMotivesByIdSet(Set<Integer> motiveIdSet) {

		Iterator<Integer> motiveIdIterator = motiveIdSet.iterator();
		Set<Motive> motiveSet = new HashSet<>();
		while (motiveIdIterator.hasNext()) {
			Integer id = motiveIdIterator.next();
			Motive currentMotive = motiveDAO.findMotiveById(id);
			motiveSet.add(currentMotive);
		}
		return motiveSet;
	}

	@Transactional
	public List<Motive> findAllMotives(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Motive>(motiveDAO.findAllMotives(startResult, maxRows));
	}

	@Transactional
	public Motive findMotiveByPrimaryKey(Integer id) {
		return motiveDAO.findMotiveByPrimaryKey(id);
	}

	@Transactional
	public Integer countMotives() {
		return ((Long) motiveDAO.createQuerySingleResult("select count(o) from Motive o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countMotives(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Motive.class);
		return ((Long) motiveDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countMotivesByName(String queryName) {
		Query query = motiveDAO.createNamedQuery("countMotivesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countMotivesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Motive.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadMotiveObjectReferencedSet(Motive motive) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventsIds = new HashSet<Integer>();
		for (Event event : motive.getEventsForMotive()) {
			eventsIds.add(event.getId());
		}
		objectReferencedSetMap.put("eventsIds", eventsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadMotiveClassReferencedSet(Motive motive) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());

		return classReferencedSetMap;
	}

	public boolean isEquals(Motive motive, Object obj) {
		if (obj == motive)
			return true;
		if (!(obj instanceof Motive))
			return false;
		Motive comparedMotive = (Motive) obj;
		if (!CheckPropertyEqual(motive.getName(), comparedMotive.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

